import prompt_toolkit
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.completion import Completer, Completion
#from prompt_toolkit.completion import WordCompleter
from prompt_toolkit.lexers import PygmentsLexer
from prompt_toolkit.history import FileHistory
from pygments.lexers.python import PythonLexer
from fuzzyfinder import fuzzyfinder
from prompt_toolkit import prompt
import click

#EnvCompleter = WordCompleter(['select', 'from', 'insert', 'update', 'delete', 'drop'], ignore_case=True)
EnvKeywords = ['fetch', 'dir', 'rename', 'rename_i']

class EnvCompleter(Completer):
    def get_completions(self, document, complete_event):
        word_before_cursor = document.get_word_before_cursor(WORD=True)
        matches = fuzzyfinder(word_before_cursor, EnvKeywords)
        for m in matches : yield Completion(m, start_position=-len(word_before_cursor))

while 1:
    user_input = prompt('>',
                        history=FileHistory('1.history.txt'),
                        auto_suggest=AutoSuggestFromHistory(),
                        #AutoSuggest.get_suggestion(self=None,buffer='Buffer',document=prompt_toolkit.document.Document(text='promptttttt')),
                        #completer=EnvCompleter,
                        completer=EnvCompleter(),
                        lexer=PygmentsLexer(PythonLexer)
                        )
    # user_input = click.edit(user_input,editor="vim")

    user_input = user_input.split(' ')
    var_returns = []
    var_point = 0
    var_return = ''
    #while user_input != []:
    for i in range(len(user_input)):
        var_returns.append('')
        if user_input[i] == 'dir':
            import sys
            var_returns[i] = sys.path[0]
        elif user_input[i] == 'fetch':
            var_point = i+1
        elif user_input[i] == 'rename':
            import os
            import sys
            if user_input[i+1] == r'*' or user_input[i+1] == 'all' :
                for rename_i in os.listdir(sys.path[0]):
                    try: exec("os.rename(sys.path[0]+'\\\\'+rename_i, sys.path[0]+'\\\\'+%s)" %(user_input[i+2]))
                    except: print(" ! rename '%s' -failure> '%s'" %(rename_i, user_input[i+2]))
            
    #    print(var_returns[0])
    
    if var_point >= len(var_returns): var_point -= 1
    var_return = var_returns[var_point]
    print(var_return)
    click.echo_via_pager(var_return)

